﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Data.OleDb;
using System.Web;
using System.Data;
using System.Data.Common;
using NLBS.Entity;
using System.Xml;

namespace NLBS.Data.Install
{
   public class LbsDataImport
    {


       private string _oleDbConntectionString;

        public string OleDbConnectionString
        {
            get { return _oleDbConntectionString; }
            set { _oleDbConntectionString = value; }
        }

       public LbsDataImport(string oledbPath, string conn)
       {
           this._oleDbConntectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;" +
                             "data source={0}", oledbPath);
           _accessDb = new GenericDatabase(OleDbConnectionString, OleDbFactory.Instance);
           _sqlDb = new SqlDatabase(conn);

       }

       #region property

       private GenericDatabase _accessDb;

       public GenericDatabase AccessDb
       {
           get { return _accessDb; }
           
       }

       private SqlDatabase _sqlDb;

       public SqlDatabase SqlDb
       {
           get { return _sqlDb; }

       }

       #endregion


       public void UpdateData()
       {
           string sqlPath = HttpContext.Current.Server.MapPath("Install/lbsUpdate/Installation01.sql");
           SqlHelper.RunAccessSQL(sqlPath, OleDbConnectionString, 6000);
       }

       public void ChangeData()
       {
           DbCommand selectdbCommand = AccessDb.GetSqlStringCommand("select * from blog_Settings");
           List<string> settingList = new List<string>();
           string links = string.Empty;
           using (IDataReader dr = AccessDb.ExecuteReader(selectdbCommand))
           {
               while (dr.Read())
               {
                   settingList.Add(dr["set_name"].ToString());
                   if (dr["set_name"].ToString() == "links")
                   {
                       ChangeLink(dr["set_value1"].ToString());
                   }
               }
           }
           //add maxCommentURLCount
           AddCommentURLCount(settingList);
         
       }


       private void AddCommentURLCount(List<string> list)
       {
           bool urlCount = list.Contains("maxCommentURLCount");
           if (!urlCount)
           {
               SqlHelper.ExecuteNonQuery(
                   @"INSERT INTO [blog_settings] 
                  ([set_name], [set_type], [set_value0], [set_value1])  
                  VALUES ('maxCommentURLCount','0','2','');", SqlDb);
           }
       }


       private void ChangeLink(string links)
       {
           //Link

           XmlDocument doc = GetLinksXml();
           XmlNode root = doc.DocumentElement;
           foreach (XmlNode item in root.ChildNodes)
           {
               if (item.Attributes["LinkType"].Value == "FriendLink")
               {
                   item.FirstChild.Value = links;
               }
           }

           doc.Save(HttpContext.Current.Server.MapPath("/App_Data/Links.xml"));
       }
   

       public XmlDocument GetLinksXml()
       {
           XmlDocument doc = new XmlDocument();
           string file = HttpContext.Current.Server.MapPath("/App_Data/Links.xml");
           doc.Load(file);

           return doc;
       }

       private List<Tag> GetTagList()
       {
           DbCommand selectdbCommand = AccessDb.GetSqlStringCommand("select tag_id,tag_Name from blog_tag");
           Database db = this.SqlDb;
           List<Tag> tags = new List<Tag>();
           using (IDataReader dr = AccessDb.ExecuteReader(selectdbCommand))
           {
               while (dr.Read())
               {
                   Tag tag = new Tag();
                   tag.TagID = Convert.ToInt32(dr["tag_id"].ToString());
                   tag.Name = dr["tag_Name"].ToString();
                   tags.Add(tag);
               }
               return tags;
           }
       }


       public void ImportLink()
       {

       }

       public void ImportTag()
       {
           DbCommand selectdbCommand = AccessDb.GetSqlStringCommand("select log_id,log_tag from blog_content");

           Database db = this.SqlDb;
           List<Tag> tagList = GetTagList();
           using (IDataReader dr = AccessDb.ExecuteReader(selectdbCommand))
           {
               while (dr.Read())
               {
                   string logtag = dr["log_tag"].ToString();
                   int logID = Convert.ToInt32(dr["log_id"].ToString());
                   if (logtag.Length > 0)
                   {
                       string[] tags = logtag.Split(new char[] { '}' });
                       foreach (string item in tags)
                       {
                           if (item.Length > 0)
                           {
                               string itemTag = item.Substring(1);
                               Tag findTag = tagList.Find(delegate(Tag tag)
                               {
                                   return tag.TagID == Convert.ToInt32(itemTag);
                               });
                               DbCommand comm = db.GetSqlStringCommand(string.Format(
                               "insert into blog_tag (log_id,tag_Name) values({0},'{1}')", logID, findTag.Name));
                               db.ExecuteNonQuery(comm);
                           }
                       }
                   }
               }
           }
       }
    }
}
